import { defineStore } from 'pinia'

// 用户状态管理
export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    accessToken: localStorage.getItem('accessToken') || '',
    refreshToken: localStorage.getItem('refreshToken') || '',
    tokenType: 'Bearer',
    expiresIn: 0
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.accessToken,
    userName: (state) => state.userInfo?.username || '',
    userType: (state) => state.userInfo?.userType || '',
    userId: (state) => state.userInfo?.userId || '',
    token: (state) => state.accessToken // 兼容旧的token getter
  },
  
  actions: {
    // 设置登录信息
    setLoginInfo(loginData) {
      const { accessToken, refreshToken, tokenType, expiresIn, userInfo } = loginData
      this.accessToken = accessToken
      this.refreshToken = refreshToken
      this.tokenType = tokenType || 'Bearer'
      this.expiresIn = expiresIn
      this.userInfo = userInfo
      
      // 保存到localStorage
      localStorage.setItem('accessToken', accessToken)
      localStorage.setItem('refreshToken', refreshToken)
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    
    // 兼容旧的setToken方法
    setToken(token) {
      this.accessToken = token
      localStorage.setItem('accessToken', token)
    },
    
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    
    // 刷新token
    refreshTokens(tokenData) {
      const { accessToken, refreshToken, expiresIn } = tokenData
      this.accessToken = accessToken
      this.refreshToken = refreshToken
      this.expiresIn = expiresIn
      
      localStorage.setItem('accessToken', accessToken)
      localStorage.setItem('refreshToken', refreshToken)
    },
    
    // 初始化用户信息（从localStorage恢复）
    initUserInfo() {
      const userInfo = localStorage.getItem('userInfo')
      if (userInfo) {
        try {
          this.userInfo = JSON.parse(userInfo)
        } catch (e) {
          console.error('解析用户信息失败:', e)
        }
      }
    },
    
    logout() {
      this.accessToken = ''
      this.refreshToken = ''
      this.userInfo = null
      this.tokenType = 'Bearer'
      this.expiresIn = 0
      
      localStorage.removeItem('accessToken')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('userInfo')
    }
  }
})

// 应用状态管理
export const useAppStore = defineStore('app', {
  state: () => ({
    collapsed: false,
    loading: false,
    breadcrumbs: []
  }),
  
  actions: {
    toggleSidebar() {
      this.collapsed = !this.collapsed
    },
    
    setLoading(loading) {
      this.loading = loading
    },
    
    setBreadcrumbs(breadcrumbs) {
      this.breadcrumbs = breadcrumbs
    }
  }
})